/*
 *  Copyright 2008 the original author or authors.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package app.layouts;

import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.richclient.application.ApplicationPage;
import org.springframework.richclient.application.ApplicationPageFactory;
import org.springframework.richclient.application.ApplicationWindow;
import org.springframework.richclient.application.PageDescriptor;
import org.springframework.richclient.application.PageListener;

/**
 *
 * @author Peter Karich, peat_hal ‘at’ users ‘dot’ sourceforge ‘dot’ net
 */
public class MyDoggyApplicationPageFactory implements ApplicationPageFactory {

    private final Log logger = LogFactory.getLog(getClass());

    public ApplicationPage createApplicationPage(ApplicationWindow window, PageDescriptor descriptor) {
        MyDoggyApplicationPage page = new MyDoggyApplicationPage(window, descriptor);

        window.addPageListener(new PageListener() {

            public void pageOpened(ApplicationPage page) {
                // normally this should be called on application start
                MyDoggyApplicationPage myDoggyApplicationPage = (MyDoggyApplicationPage) page;
                // determine wether we can load from file or 
                // we should start with only one predefined page
                boolean appliedLayout = false;

                try {
                    if (myDoggyApplicationPage.loadLayout()) {
                        appliedLayout = true;
                    }
                } catch (IOException ex) {
                    logger.warn("Failed to restore layout from file!", ex);
                }
                
                if(!appliedLayout) {
                    myDoggyApplicationPage.buildInitialLayout();
                }
            }

            public void pageClosed(ApplicationPage aPage) {                
                // TODO this won't be called?
                // normally this should be called on exit of the application              
            }
        });

        return page;
    }
}
